// const baseUrl = 'http://121.37.118.34:9005'
const baseUrl = 'https://wvuw.oucuiya.com'
uni.setStorageSync('baseUrl', baseUrl)

// 不需要token验证的白名单接口
const whiteList = [
    '/app/user/login',
]

const request = (url = '', date = {}, type = 'GET', header = {}) => {
    // 构建请求头
    const token = uni.getStorageSync('token')
    const requestHeader = {
        ...header,
        "Authorization": token
    }

    // 检查是否需要token验证
    // if (!whiteList.includes(url) && !token) {
    //     handleNoAuth('请先登录')
    //     return Promise.resolve({
    //         code: 401,
    //         message: '请先登录'
    //     })
    // }

    return new Promise((resolve, reject) => {
        uni.request({
            method: type,
            url: baseUrl + url,
            data: date,
            header: requestHeader,
            dataType: 'json',
        }).then((response) => {
            setTimeout(() => {
                uni.hideLoading();
            }, 200);
            
            const res = response.data;
            if (res.code === '401' || res.code === 401) {
              uni.removeStorageSync('token');
              setTimeout(() => {
                uni.reLaunch({
                  url: '/pages/index/index',
                  fail: (err) => {
                    console.error('跳转首页失败:', err);
                  }
                });
              }, 500);
              uni.showToast({
                title: '登录过期，请重新登录',
                icon: 'none',
                duration: 2000
              });
            }
            resolve(res);
        }).catch(error => {
            uni.hideLoading();
            const errorMsg = {
                code: 500,
                message: '网络请求失败，请稍后重试'
            }
            reject(errorMsg)
        })
    });
}
// 统一处理未授权情况
// const handleNoAuth = (message) => {
//     uni.setStorageSync('token', '')// 清除token
//     uni.showToast({// 提示用户
//         title: message,
//         icon: 'none',
//         duration: 2000
//     })
//     setTimeout(() => {// 延迟跳转到登录页
//         uni.reLaunch({
//             url: '/pages/index/index'//目前登录功能逻辑待定，先跳转到首页
//         })
//     }, 1500)
// }
export default request
